package sshdata

import (
	"bytes"
	"context"
	"fmt"
	scp "github.com/bramvdbogaerde/go-scp"
	"golang.org/x/crypto/ssh"
	"log"
	"os"
)

type SshData struct {
	username string
	password string
	host     string
	port     int
}

func GetConnection() *ssh.Client {
	//var hostKey ssh.PublicKey
	// An SSH client is represented with a ClientConn.
	//
	// To authenticate with the remote server you must pass at least one
	// implementation of AuthMethod via the Auth field in ClientConfig,
	// and provide a HostKeyCallback.
	config := &ssh.ClientConfig{
		User: "ywx1293154",
		Auth: []ssh.AuthMethod{
			ssh.Password("lyw123456"),
		},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}
	client, err := ssh.Dial("tcp", "123.60.114.105:2222", config)
	if err != nil {
		log.Fatal(" Failed to dial: ", err)
	}
	// Each ClientConn can support multiple interactive sessions,
	// represented by a Session.
	session, err := client.NewSession()
	if err != nil {
		log.Fatal("Failed to create session: ", err)
	}
	defer session.Close()
	// Once a Session is created, you can execute a single command on
	// the remote side using the Run method.
	var b bytes.Buffer
	session.Stdout = &b
	if err := session.Run("/usr/bin/whoami"); err != nil {
		log.Fatal("Failed to run: " + err.Error())
	}
	log.Println("connect to remote server 123.60.114.105")
	return client
}

func DownloadFile(remoteFileNameWithAbsolutePath string, localFileName string, conn *ssh.Client) {
	client, err := scp.NewClientBySSH(conn)
	if err != nil {
		log.Fatal("error create sftp client")
	}
	defer client.Close()
	dstFile, err := os.Create(localFileName)
	if err != nil {
		fmt.Println("fail to create local script", err)
		dstFile, _ = os.Create(localFileName)
	}
	defer dstFile.Close()
	err = client.CopyFromRemote(context.Background(), dstFile, remoteFileNameWithAbsolutePath)

	if err != nil {
		log.Fatal("Error while copying script ", err)
	}
}

func UploadFile(remoteFileNameWithAbsolutePath string, localFileName string, conn *ssh.Client, permissions string) bool {
	client, err := scp.NewClientBySSH(conn)
	defer client.Close()
	if err != nil {
		log.Println("error create sftp client error msg = ", err)
		return false
	}
	localFile, err := os.Open(localFileName)
	if err != nil {
		log.Println("error when opening ", localFile, " error msg = ", err)
		return false
	}
	err = client.CopyFromFile(context.Background(), *localFile, remoteFileNameWithAbsolutePath, permissions)
	if err != nil {
		log.Println("error when upload file ", localFileName, " error msg = ", err)
		return false
	}
	return true
}
